#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File ：ProductLogic.py
@Author ：zqy
@Email : zqingy@work@163.com 
@note: 
"""
from application.Parser.ProductParser import ProductValidator
from application.logic import BaseLogic
from application.mapper.ProductMapper import ProductMapper
from application.model.ProductModel import Product


class ProductLogic(BaseLogic):
    """
    产品逻辑层
    """
    model: Product = Product  # 定义模型
    mapper: ProductMapper = ProductMapper  # 定义mapper
    # 实例化redis客户端
    validator: ProductValidator = ProductValidator

    @classmethod
    def get_list(cls, params) -> dict:
        """
        获取用户信息列表
        :param params
        :return: {
                    items: [...],
                    total, page_size, current_page
                }
        """
        _filter = []
        if not params.get("show_all"):
            _filter.append(cls.model.usable == 1)
        if params.get("is_hot"):
            _filter.append(cls.model.is_hot == True)
        elif params.get("is_new"):
            _filter.append(cls.model.is_new == True)
        else:
            if params.get("search_keyword"):
                _filter.append(ProductLogic.model.name.like(f"%{params.get('search_keyword')}%"))
            if params.get("category_id"):
                _filter.append(ProductLogic.model.category_id == params.get("category_id"))

        current_page = params.get("current_page", 1)
        page_size = params.get("page_size", 10)
        result: dict = dict(items=[], total=cls.mapper.count(_filter), page_size=page_size,
                            current_page=current_page)
        products = cls.mapper.get_info_list(page_size=page_size, current_page=current_page, filter=_filter)

        for p in products:
            result['items'].append(p.to_dict())
        return result
